package com.distribute.portal.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.distribute.common.pojo.DistributeResult;
import com.distribute.common.util.CookieUtils;
import com.distribute.common.util.ExceptionUtil;
import com.distribute.common.util.HttpClientUtil;
import com.distribute.pojo.DbOrder;
import com.distribute.pojo.DbUser;
import com.distribute.portal.annotation.Token;
import com.distribute.portal.pojo.BootstrapResult;
import com.distribute.portal.pojo.ItemInfo;
import com.distribute.pojo.Order;
import com.distribute.portal.service.ItemService;
import com.distribute.portal.service.OrderService;
import com.distribute.portal.service.UserService;

@Controller
@RequestMapping("/order")
public class OrderController {

	@Autowired
	private OrderService orderService;
	@Autowired
	private ItemService itemService;
	@Autowired
	private UserService userService;

	@RequestMapping("/order-detail/{orderId}")
	public String showOrderDetail(@PathVariable Long orderId, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		DbUser user = (DbUser) request.getAttribute("user");
		Order order = orderService.getOrderById(orderId);
		model.addAttribute("user", user);
		model.addAttribute("order", order);
		return "order-detail";
	}

	// 根据userid查询订单
	@RequestMapping(value = "/order-list/{userId}" /*produces = MediaType.TEXT_HTML_VALUE + ";charset=utf-8"*/)
	public String showOrderList(@PathVariable Long userId, @RequestParam(defaultValue="1") Integer page , HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			BootstrapResult result = orderService.getOrderByUserId(userId, page);
			model.addAttribute("orderList", result.getOrderList());
			model.addAttribute("page", page);
			model.addAttribute("totalPages", ((result.getTotalPages()+6-1)/6));
			model.addAttribute("user", request.getAttribute("user"));
		} catch (Exception e) {
			return "fail"+ExceptionUtil.getStackTrace(e);
		}
		return "order-list";
	}
///{token} @PathVariable String token, 
	@RequestMapping("/order-settlement/{itemId}")
	@Token(save=true)
	public String showOrderSettlement(@PathVariable Long itemId,HttpServletRequest request,
			HttpServletResponse response, Model model) {
		ItemInfo itemInfo = itemService.getItemById(itemId);
		String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
		DbUser user = userService.getUserByToken(token);
		model.addAttribute("user", user);
		System.out.println(user.getPhone()+user.getEmail()+"888888888888888888888");
		model.addAttribute("itemInfo", itemInfo);
		return "order-settlement";
	}

	/*
	 * @RequestMapping("/order-cart") public String showOrderCart(HttpServletRequest
	 * request, HttpServletResponse response, Model model) { //取购物车商品列表
	 * List<CartItem> list = cartService.getCartItemList(request, response); //传递给页面
	 * model.addAttribute("cartList", list);
	 * 
	 * return "order-cart"; }
	 */

	@RequestMapping("/create")
	@Token(remove=true)
	public String createOrder(Order order, Model model, @RequestParam String token, HttpServletRequest request) {
		try {
			DbUser user = userService.getUserByToken(token);
			/*
			 * //从Request中取用户信息 DbUser user = (DbUser) request.getAttribute("user");
			 */
			// 在order对象中补全用户信息
			order.setUserId(user.getId());
			order.setBuyerNick(user.getUsername());
			// 调用服务
			String orderId = orderService.createOrder(order);
			model.addAttribute("orderId", orderId);
			model.addAttribute("itemId", order.getOrderItem().getItemId());
	/*		model.addAttribute("status", order.getStatus());*/
			model.addAttribute("userMessage", order.getBuyerMessage());
			model.addAttribute("date", new DateTime().toString("yyyy-MM-dd"));//new DateTime().toString("yyyy-MM-dd")
			return "order-success";

		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("message", "创建订单出错。请稍后重试！");
			return "error/exception";
		}
	}

	@RequestMapping("/error-repeat")
	public String showErrorRepeat() {
		return "error-repeat";
	}

}
